package base.auth;


import base.model.Header;
import base.model.NettyMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by wuhui on 2016/8/4.
 */
public class LoginAuthRespHandler extends ChannelHandlerAdapter {
    //已登录ip
    private Map<String,Boolean> nodeChenk = new ConcurrentHashMap<>();

    //ip白名单
    private  String[] whiteList  = {

    };

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage) msg;
        if(nettyMessage.getHeader()!=null&&nettyMessage.getHeader().getType()==1){
            String nodeIndex = ctx.channel().remoteAddress().toString();
            NettyMessage loginResp  = null;
            //重复登录,拒绝
            if(nodeChenk.containsKey(nodeIndex)){
                loginResp = buildLoginResp((byte)-1);
            }else{
                InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                String ip = inetSocketAddress.getAddress().getHostAddress();
                boolean isOk = false;
                for (String WIP :whiteList){
                    if(WIP.equals(ip)){
                        isOk = true;
                        break;
                    }
                }
                loginResp = isOk?buildLoginResp((byte) 0):buildLoginResp((byte)-1);
                if(isOk){
                    nodeChenk.put(nodeIndex,true);
                }
                ctx.writeAndFlush(loginResp);
            }
        }else{
            ctx.fireChannelRead(msg);
        }
    }
    /**
     * 构造登录消息
     * @return
     */
    private NettyMessage buildLoginResp(byte resultb){
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        //header.setType();
        message.setHeader(header);
        message.setBody(resultb);
        return  message;
    }



}
